package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.model.entity.ViewAppointment;
import com.atguigu.lease.web.app.mapper.ViewAppointmentMapper;
import com.atguigu.lease.web.app.service.ApartmentInfoService;
import com.atguigu.lease.web.app.service.ViewAppointmentService;
import com.atguigu.lease.web.app.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.app.vo.appointment.AppointmentDetailVo;
import com.atguigu.lease.web.app.vo.appointment.AppointmentItemVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author gqs
 * @description 针对表【view_appointment(预约看房信息表)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
public class ViewAppointmentServiceImpl extends ServiceImpl<ViewAppointmentMapper, ViewAppointment>
    implements ViewAppointmentService {
  @Autowired private ViewAppointmentMapper viewAppointmentMapper;
  @Autowired private ApartmentInfoService apartmentInfoService;

  @Override
  /**
   * 保存或更新视图预约信息 此方法旨在将视图预约信息与当前登录用户的ID关联并尝试保存或更新该信息
   *
   * @param viewAppointment 视图预约对象，包含预约的相关信息
   * @return 操作是否成功执行的布尔值
   */
  public boolean saveOrUpdateViewAppointment(ViewAppointment viewAppointment) {
    // 将预约信息与当前登录用户的ID关联，确保预约信息的用户归属正确
    viewAppointment.setUserId(LoginUserContext.getLoginUser().getUserId());
    // 尝试保存或更新预约信息，并返回操作结果
    return this.saveOrUpdate(viewAppointment);
  }

  @Override
  public List<AppointmentItemVo> selectViewAppointmentList(Long userId) {
    List<AppointmentItemVo> list = viewAppointmentMapper.selectViewAppointmentList(userId);
    return list;
  }

  @Override
  /**
   * 根据ID获取预约详情视图对象
   *
   * @param id 预约记录的ID
   * @return 如果存在对应的预约记录，则返回填充了公寓信息的预约详情视图对象，否则返回null
   */
  public AppointmentDetailVo getAppointmentDetailVoById(Long id) {
    // 通过ID查询预约记录
    ViewAppointment viewAppointment = viewAppointmentMapper.selectById(id);
    // 如果预约记录不存在，则直接返回null
    if (viewAppointment == null) {
      return null;
    }
    // 通过预约记录中的公寓ID查询公寓信息
    ApartmentItemVo apartmentItemVo =
        apartmentInfoService.selectApartmentItemById(viewAppointment.getApartmentId());

    // 创建预约详情视图对象
    AppointmentDetailVo appointmentDetailVo = new AppointmentDetailVo();
    // 将公寓信息复制到预约详情视图对象
    BeanUtils.copyProperties(viewAppointment, appointmentDetailVo);

    // 将公寓信息对象设置到预约详情视图对象中
    appointmentDetailVo.setApartmentItemVo(apartmentItemVo);
    // 返回填充了公寓信息的预约详情视图对象
    return appointmentDetailVo;
  }
}
